<template>
  <!-- 首页 -->
  <div class="homeContainer">
    <!-- 轮播图 -->
    <Banner :imgList="imgList" />
    <!-- 热门推荐 -->
    <div class="hotRecommendation container">
      <!-- 标题导航 -->
      <div class="titleNav">
        <!-- 标题 -->
        <div class="title">
          <div class="circle"></div>
          <h3>热门歌单</h3>
        </div>
        <!-- 导航 -->
        <ul class="nav">
          <li v-for="tag in hotTag.slice(0, 5)" :key="tag.id" class="pointer">
            <a @click.prevent="toSonglistCategory(tag.name)">{{ tag.name }}</a>
          </li>
          <!-- 更多 -->
          <div
            class="more pointer"
            @click.stop="$router.push('/allSonglist?cat=全部')"
          >
            <span>更多</span>
            <right theme="outline" size="16" fill="#999" class="iconfont" />
          </div>
        </ul>
      </div>
      <!-- 歌单列表 -->
      <div class="songListContainer">
        <!-- 歌单 -->
        <div class="songList">
          <SonglistCard
            v-for="item in recSongList"
            :key="item.id"
            :id="item.id"
            :desc="item.desc"
            :cover="item.cover"
            :playCount="item.playCount"
            @click="toSonglistDetail(item.id)"
          />
        </div>
        <!-- 热门歌曲 -->
        <div class="hotSong">
          <!-- 榜单 -->
          <div class="list" v-for="item in toplist" :key="item.toplistId">
            <!-- 榜单标题 -->
            <div class="listTitle pointer" @click="toToplist(item.toplistId)">
              {{ item.toplistName }}
            </div>
            <div class="top3">
              <ul>
                <li
                  class="pointer"
                  v-for="(song, index) in item.songs"
                  :key="song.id"
                  @click="playSong(song.id)"
                >
                  <span class="ranking one">{{ index + 1 }}. &nbsp;</span>
                  <span class="songName">{{ song.name }}</span>
                  <span>&nbsp;-&nbsp;</span>
                  <span
                    class="singer"
                    v-for="(singers, index) in song.ar"
                    :key="singers.id"
                  >
                    {{ singers.name }}
                    <span v-if="index === singers.length - 1">、</span>
                  </span>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 新歌推荐 -->
    <div class="newSongRec container">
      <!-- 标题导航 -->
      <div class="titleNav">
        <div class="title">
          <h3
            @click="_getNewSongRec(0)"
            class="pointer"
            :class="{ newSongTypeActive: currentType === 0 }"
          >
            新歌推荐
          </h3>
        </div>
        <ul class="nav">
          <li>
            <a
              class="pointer"
              @click.prevent="_getNewSongRec(7)"
              :class="{ newSongTypeActive: currentType === 7 }"
              >华语</a
            >
          </li>
          <li>
            <a
              class="pointer"
              @click.prevent="_getNewSongRec(96)"
              :class="{ newSongTypeActive: currentType === 96 }"
              >欧美</a
            >
          </li>
          <li>
            <a
              class="pointer"
              @click.prevent="_getNewSongRec(8)"
              :class="{ newSongTypeActive: currentType === 8 }"
              >日本</a
            >
          </li>
          <li>
            <a
              class="pointer"
              @click.prevent="_getNewSongRec(16)"
              :class="{ newSongTypeActive: currentType === 16 }"
              >韩国</a
            >
          </li>
        </ul>
      </div>
      <!-- 歌曲列表 -->
      <ul class="list" ref="ulList" style="height: 520px">
        <li
          v-for="item in newSongList"
          @click.stop="playSong(item.id)"
          :key="item.id"
        >
          <SongCard
            :cover="item.album.blurPicUrl"
            :songName="item.name"
            :singers="item.artists"
          />
        </li>
      </ul>
      <!-- 获取更多 -->
      <div class="getMore">
        <span class="pointer" @click="_getMoreNewSong">获取更多</span>
      </div>
    </div>
  </div>
</template>

<script name="Home" setup>
import { Right } from '@icon-park/vue-next';
import Banner from '@/components/Banner.vue';
import SonglistCard from '@/components/SonglistCard.vue';
import SongCard from '@/components/SongCard.vue';
import {
  reactive,
  onMounted,
  ref,
  getCurrentInstance,
  onBeforeUnmount,
} from 'vue';
import { getBanner } from '@/api/images';
import { newSongRec, playlistSong } from '@/api/song';
import { allToplist } from '@/api/toplist';
import { getRecSonglist, hotSonglistTag } from '@/api/songlist.js';
import { useRouter } from 'vue-router';
import songlistStore from '@/stores/songlistStore';
import { usePlaySong } from '@/hooks/usePlaySong';
import { ElMessage } from 'element-plus';

const router = useRouter();
const playlistStore = songlistStore();
const { proxy } = getCurrentInstance();
const abortController = new AbortController();
const { playSong } = usePlaySong();

// 轮播图
let imgList = reactive([]);
async function getImgList() {
  const res = (await getBanner(0)).data;
  res.banners?.map((img) => {
    imgList.push({
      id: img.targetId,
      url: img.imageUrl,
    });
  });
}

// 跳转歌单分类
function toSonglistCategory(category) {
  playlistStore.changeCategory(category);
  router.push('/allSonglist?cat=' + encodeURI(category));
}

// 热门歌单分类
let hotTag = reactive([]);
async function getHotSonglistTag() {
  const res = (await hotSonglistTag()).data;
  res.tags.map((tag) => {
    hotTag.push({
      id: tag.id,
      name: tag.name,
    });
  });
}

// 推荐歌单
let recSongList = reactive([]);
async function getSongList() {
  const res = (await getRecSonglist(10)).data;
  res.result.map((item) => {
    recSongList.push({
      id: item.id,
      desc: item.name,
      cover: item.picUrl,
      playCount: item.playCount,
    });
  });
}

// 首页榜单
let toplistId = reactive([]); // 首页榜单ID
let toplist = reactive([]);
async function getToplist() {
  const res = (await allToplist()).data;
  res.list?.map((item) => {
    if (
      item.name === '飙升榜' ||
      item.name === '新歌榜' ||
      item.name === '原创榜'
    ) {
      toplistId.push({
        id: item.id,
        name: item.name,
      });
    }
  });
  // 获取榜单前三歌曲
  toplistId.forEach((item) => {
    playlistSong(item.id, 3, 0).then(({ data }) => {
      toplist.push({
        toplistId: item.id,
        toplistName: item.name,
        songs: data.songs,
      });
    });
  });
}

// 跳转到榜单
function toToplist(id) {
  router.push(`/songTopList?id=${id}`);
}

// 新歌推荐
const ulList = ref(); // 新歌列表
let newSongList = reactive([]); // 页面展示的列表数据
let fullList = reactive([]); // 完整列表数据
let limit = ref(15); // 限制数量
let currentType = ref(0); // 当前类型
async function getNewSongRec(type, isFirst = false) {
  // type -> 新歌类型 | isFirst -> 是否第一次请求
  if (currentType.value === type && !isFirst) return;
  currentType.value = type; // 切换类型
  // 清空原数组
  newSongList.splice(0);
  fullList.splice(0);
  // 恢复 limit 初始值
  limit.value = 15;
  let height = parseInt(ulList.value.style.height);
  if (height !== 520) {
    ulList.value.style.height = '520px';
  }
  const res = (await newSongRec(type)).data;
  const arr = res.data;
  arr.forEach((song) => {
    fullList.push(song);
  });
  // 默认只获取 15 条数据（limit值）
  while (newSongList.length < limit.value) {
    newSongList.push(fullList[newSongList.length]);
  }
}
const _getNewSongRec = proxy.lodash.debounce(getNewSongRec, 500); // 防抖函数

// 获取更多新歌
function getMoreNewSong() {
  if (newSongList.length === fullList.length) {
    ElMessage({
      type: 'warning',
      message: '没有更多咯',
    });
    return;
  }
  let height = parseInt(ulList.value.style.height);
  ulList.value.style.height = `${height + 520}px`;
  limit.value += 15;
  while (
    newSongList.length < limit.value &&
    newSongList.length !== fullList.length
  ) {
    newSongList.push(fullList[newSongList.length]);
  }
}
const _getMoreNewSong = proxy.lodash.throttle(getMoreNewSong, 1000); // 节流函数

// 跳转到歌单详情
function toSonglistDetail(id) {
  router.push(`/songListDetail/${id}`);
}

// 立即执行方法
function init() {
  getImgList();
  getSongList();
  getToplist();
  getHotSonglistTag();
  getNewSongRec(0, true);
}

onMounted(() => {
  init();
});

onBeforeUnmount(() => {
  abortController.abort(); // 终止请求
});
</script>

<style lang="scss" scoped>
// 标题导航
.titleNav {
  width: $titleWidth;
  height: 50px;
  border-bottom: 3px solid $main-color;
  margin: 0 auto;
  display: flex;
  box-sizing: border-box;
  align-items: center;

  // 标题
  .title {
    width: 100px;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .circle {
      width: 18px;
      height: 18px;
      background-color: $main-color;
      border-radius: 50%;
    }

    h3 {
      font-size: 18px;
      color: #333;
    }
  }

  // 导航
  .nav {
    width: 1050px;
    height: 100%;
    display: flex;
    align-items: center;
    padding-left: 10px;
    position: relative;

    li {
      padding: 10px 20px;

      a {
        font-size: 16px;
        color: #999;
        transition: all 0.2s;

        &:hover {
          color: $main-color;
        }
      }
    }

    // 更多
    .more {
      width: 45px;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      color: #999;
      position: absolute;
      right: 0;
    }
  }
}

// 热门推荐
.hotRecommendation {
  height: 490px;
  margin: 0 auto;
  border: 1px solid #eee;
  background-color: #fff;

  // 歌单列表
  .songListContainer {
    width: $titleWidth;
    height: 420px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    margin: 10px auto;

    // 歌单
    .songList {
      width: 860px;
      height: 100%;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;
    }

    // 热门歌曲
    .hotSong {
      width: 280px;
      height: 410px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
      border-radius: 10px;

      // 榜单
      .list {
        width: 270px;
        height: 120px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        &:nth-child(1) .listTitle {
          background-image: linear-gradient(
            -225deg,
            $main-color 0%,
            #71b1ff 100%
          );
        }

        &:nth-child(2) .listTitle {
          background-image: linear-gradient(to top, #fbc2eb 0%, #a6c1ee 100%);
        }

        &:nth-child(3) .listTitle {
          background-image: linear-gradient(
            -225deg,
            #9efbd3 0%,
            #57e9f2 48%,
            #45d4fb 100%
          );
        }

        // 榜单标题
        .listTitle {
          width: 120px;
          height: 120px;
          text-align: center;
          line-height: 120px;
          font-weight: bold;
          border-radius: 10px;
          font-size: 20px;
          color: #fff;
          transition: 0.5s;

          &:hover {
            opacity: 0.7;
          }
        }

        .top3 {
          width: 145px;
          height: 100%;
          text-align: left;

          ul {
            width: 100%;
            height: 100%;
            padding: 0;
            margin: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-around;
            overflow: hidden;

            li {
              width: 100%;
              max-width: 150px;
              height: 20px;
              line-height: 20px;
              font-size: 16px;
              color: #333;
              display: flex;
              color: #999;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              display: inline-block;

              .songName,
              .singer {
                color: #333;
              }

              .one,
              .two,
              .three {
                font-weight: bold;
                color: $main-color;
              }

              &:hover span {
                color: $main-color;
              }
            }
          }
        }
      }
    }
  }
}

// 新歌推荐
.newSongRec {
  padding-bottom: 10px;
  border: 1px solid #eee;
  margin: 20px auto;
  background-color: #fff;

  // 标题导航
  .titleNav {
    border-bottom: none;

    .nav {
      padding: 0;
    }
  }

  // 歌曲列表
  .list {
    width: 1150px;
    margin: 0 auto;
    padding: 0;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-around;
    overflow: hidden;
  }

  // 获取更多
  .getMore {
    width: 100%;
    height: 30px;
    line-height: 30px;
    text-align: center;
    font-size: 14px;

    span {
      padding: 5px 15px;
      background-color: $light-color;
      border-radius: 10px;
      color: $main-color;
      transition: background-color 0.3s, color 0.3s;

      &:hover {
        background-color: $main-color;
        color: #fff;
      }
    }
  }
}

.newSongTypeActive {
  color: $main-color !important;
}
</style>
@/api/images
